Page({
  data: {
    screenWidth: 10,
    screenHeight: 10,

    search: "",
    finishNum: 0,
    allMissions: [],
    unfinishedMissions: [],
    finishedMissions: [],

    wx_openid: "",
    other_openid: "",
    _openidA : getApp().globalData._openidA,
    _openidB : getApp().globalData._openidB,
    images: getApp().globalData.images,
    gifs: getApp().globalData.gifs,

    openIdWithUsers: [['共同任务', '共同任务'], ['oVZEY5L-kzoMOTC4tJKH04o4hOyQ', '阿拉长'], ['oVZEY5OhyCbkRV7YkQLAmnEDCzEM', '诺伯德']],
    isShow: [false, false, false, false, false, false],
    slideButtons: [
      {extClass: 'markBtn', text: '标记', src: "Images/icon_mark.svg"},
      {extClass: 'starBtn', text: '星标', src: "Images/icon_star.svg"},
      {extClass: 'removeBtn', text: '删除', src: 'Images/icon_del.svg'}
    ],
  },

  //页面加载时运行
  async onShow(){
    let _other_openid = ""
    await wx.cloud.callFunction({name: 'getOpenId'}).then(async _openid => {
      await wx.cloud.callFunction({name: 'getList', data: {list: getApp().globalData.collectionMissionList}}).then(data => {
        if (_openid.result === this.data._openidA) {
          _other_openid = this.data._openidB
        } else {
          _other_openid = this.data._openidA
        }
        this.setData({
          allMissions: data.result.data, 
          wx_openid: _openid.result,
          other_openid: _other_openid,
        })
        this.filterMission()
        this.getScreenSize()
      })
    })
  },

  //获取页面大小
  async getScreenSize(){
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          screenWidth: res.windowWidth,
          screenHeight: res.windowHeight
        })
      }
    })
  },
  // 改变折叠的显示状态
  async changeToggle(element) {
    const isShow = this.data.isShow
    let index = element.currentTarget.dataset.index + element.currentTarget.dataset.type*3
    isShow[index] = !isShow[index]
    this.setData({
      isShow: isShow
    })
  },
  //转到任务详情
  async toDetailPage(element, isUpper) {
    const missionIndex = element.currentTarget.dataset.index
    const mission = isUpper ? this.data.unfinishedMissions[missionIndex] : this.data.finishedMissions[missionIndex]
    wx.navigateTo({url: '../MissionDetail/index?id=' + mission._id})
  },
  //转到任务详情[上]
  async toDetailPageUpper(element) {
    this.toDetailPage(element, true)
  },  
  //转到任务详情[下]
  async toDetailPageLower(element) {
    this.toDetailPage(element, false)
  },
  //转到添加任务
  async toAddPage() {
    wx.navigateTo({url: '../MissionAdd/index'})
  },

  //完成任务插入一条任务记录
  addExexcutedMissionRecord(mission, from, to){
    wx.cloud.callFunction({
      name: 'addExecutedRecord', 
      data: {
        list: getApp().globalData.collectionExecutedRecordList, 
        title: mission.title,
        desc: mission.desc,
        taskType: mission.taskType,
        credit: mission.credit,
        record_id: mission._id,
        from: from,
        to: to,
      }
    })
  },
  
  // 更新mission任务信息
  updateMission(mission){
    if (Number(mission.taskNum)-1 >= 1) {
      wx.cloud.callFunction({
        name: 'updateById', 
        data: {
          _id: mission._id, taskNum: Number(mission.taskNum)-1, 
          finishNum: mission.finishNum+1, 
          available: mission.available, 
          openidFinishStatus: [],
          list: getApp().globalData.collectionMissionList
        }
    })
      mission.taskNum -= 1
      mission.finishNum += 1
    } else {
      wx.cloud.callFunction({
        name: 'updateById', 
        data: {
          _id: mission._id, taskNum: 0, 
          finishNum: mission.finishNum+1, 
          openidFinishStatus: [],
          available: false, 
          list: getApp().globalData.collectionMissionList
        }
      })
      //触发显示更新
      mission.available = false
      mission.taskNum = 0
      mission.finishNum += 1
    }
  },

  //设置搜索
  onSearch(element){
    this.setData({
      search: element.detail.value
    })

    this.filterMission()
  },

  //将任务划分为：完成，未完成
  filterMission(){
    let missionList = []
    if(this.data.search != ""){
      for(let i in this.data.allMissions){
        if(this.data.allMissions[i].title.match(this.data.search) != null){
          missionList.push(this.data.allMissions[i])
        }
      }
    }else{
      missionList = this.data.allMissions
    }

    missionList.sort(function(a,b){return b.star-a.star})
    this.setData({
      unfinishedMissions: missionList.filter(item => item.available === true),
      finishedMissions: missionList.filter(item => item.available === false),
    })
  },

  //响应左划按钮事件[上]
  async slideButtonTapUpper(element) {
    this.slideButtonTap(element, true)
  },

  //响应左划按钮事件[下]
  async slideButtonTapLower(element) {
    this.slideButtonTap(element, false)
  },

  //响应左划按钮事件逻辑
  async slideButtonTap(element, isUpper){
    //得到UI序号
    const {index} = element.detail
    //根据序号获得任务
    const missionIndex = element.currentTarget.dataset.index
    const mission = isUpper === true ? this.data.unfinishedMissions[missionIndex] : this.data.finishedMissions[missionIndex]

    await wx.cloud.callFunction({name: 'getOpenId'}).then(async openid => {

        //处理完成点击事件
        if (index === 0) {
            if(isUpper) {
                this.finishMission(element)
            }else{
              getApp().showFinishInfo('任务已经完成','error',2000)
            }

        }else if(mission._openid === openid.result){
            //处理星标按钮点击事件
            if (index === 1) {
                wx.cloud.callFunction({name: 'editStar', data: {_id: mission._id, list: getApp().globalData.collectionMissionList, value: !mission.star}})
                //更新本地数据
                mission.star = !mission.star
                this.filterMission()
            }
            
            //处理删除按钮点击事件
            else if (index === 2) {
                wx.cloud.callFunction({name: 'deleteElement', data: {_id: mission._id, list: getApp().globalData.collectionMissionList}})
                //更新本地数据
                if(isUpper) this.data.unfinishedMissions.splice(missionIndex, 1) 
                else this.data.finishedMissions.splice(missionIndex, 1) 
                //如果删除完所有事项，刷新数据，让页面显示无事项图片
                if (this.data.unfinishedMissions.length === 0 && this.data.finishedMissions.length === 0) {
                    this.setData({
                    allMissions: [],
                    unfinishedMissions: [],
                    finishedMissions: []
                    })
                }
            }

            //触发显示更新
            this.setData({finishedMissions: this.data.finishedMissions, unfinishedMissions: this.data.unfinishedMissions})

        //如果编辑的不是自己的任务，显示提醒
        }else{
          getApp().showFinishInfo('只能编辑自己的任务','error',2000)
        }
    })
  },

  //完成任务
  async finishMission(element) {
    //根据序号获得触发切换事件的待办
    const missionIndex = element.currentTarget.dataset.index
    const mission = this.data.unfinishedMissions[missionIndex]

    await wx.cloud.callFunction({name: 'getOpenId'}).then(async openid => {
      if(mission._openid != openid.result  & mission.taskType === "监督任务"){
        //完成对方任务，奖金打入对方账号
        wx.cloud.callFunction({name: 'editCredit', data: {_openid: this.data.other_openid, value: mission.credit, list: getApp().globalData.collectionUserList}})
        this.addExexcutedMissionRecord(mission, openid.result, mission._openid)
        this.updateMission(mission)

        this.filterMission()
        //显示提示
        getApp().showFinishInfo('任务完成','success',2000)
      } else if(mission._openid === openid.result & mission.taskType === "赏金任务"){
        //对方完成赏金任务后，奖金打入对方账号
        wx.cloud.callFunction({name: 'editCredit', data: {_openid: this.data.other_openid, value: mission.credit, list: getApp().globalData.collectionUserList}})
        this.addExexcutedMissionRecord(mission, this.data.other_openid, mission._openid)
        this.updateMission(mission)
        this.filterMission()
        //显示提示
        getApp().showFinishInfo('任务完成','success',2000)
      } else if(mission.taskType === "共同任务"){
        // 更新共同任务的状态
        mission.openidFinishStatus = getApp().globalData._openidA === openid.result ? 
              [[mission.openidFinishStatus[0][0], !mission.openidFinishStatus[0][1]], mission.openidFinishStatus[1]] : 
              [mission.openidFinishStatus[0], [mission.openidFinishStatus[1][0], !mission.openidFinishStatus[1][1]]]

        if (mission.openidFinishStatus[0][1] & mission.openidFinishStatus[1][1]) {
          //双方完成共同任务后，奖金打入双方账号
          wx.cloud.callFunction({name: 'editCredit', data: {_openid: getApp().globalData._openidA, value: mission.credit, list: getApp().globalData.collectionUserList}})
          wx.cloud.callFunction({name: 'editCredit', data: {_openid: getApp().globalData._openidB, value: mission.credit, list: getApp().globalData.collectionUserList}})
          this.addExexcutedMissionRecord(mission, getApp().globalData._openidA, getApp().globalData._openidB)
          mission.openidFinishStatus = [[getApp().globalData._openidA, false], [getApp().globalData._openidB, false]]
          this.updateMission(mission)
          this.filterMission()

          getApp().showFinishInfo('任务共同完成','success',2000)
        } else {
          wx.cloud.callFunction({
            name: 'updateById', 
            data: {
              _id: mission._id, taskNum: Number(mission.taskNum), 
              finishNum: mission.finishNum, 
              available: mission.available, 
              openidFinishStatus: mission.openidFinishStatus,
              list: getApp().globalData.collectionMissionList
            }
          })
          this.filterMission()
          getApp().showFinishInfo('任务还需另一方确认','none',2000)
        }
      } else {
        if (mission._openid === openid.result) {
          getApp().showFinishInfo('不能完成自己的监督任务','none',2000)
        } else {
          getApp().showFinishInfo('不能完成别人的赏金任务','none',2000)
        }
      }
    })
  },
})